-- k1,k2,k3,k4进行抢答，k5为1可以开始抢答
-- 点亮抢答人的led灯，数码管显示抢答人的按键号码


library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;

entity answer is
    port(
        k1, k2, k3, k4, k5 : in std_logic;
        num_led : out std_logic_vector(3 downto 0); -- 抢答人led
        led7 : out std_logic_vector(7 downto 0);    -- gfedcba,数码管
    );
end answer;

architecture behave of answer is
    type state_type is (
        s0, -- 抢答按键未按下 
        s1, -- 抢答状态
        s2  -- 已经有人抢答成功
    );
    signal state : state_type;
    signal num_led_temp : std_logic_vector(3 downto 0);
    signal led7_temp : std_logic_vector(7 downto 0);

begin

    -- 改变状态
    change_state: process(k1, k2, k3, k4, k5) 
    begin
        case k5 is
            when '0' => state <= s0;
            when '1' => if state = s0 then
                            if k1 = '1' or k2 = '1' or k3 = '1' or k4 = '1'  then 
                                state <= s1; -- 抢答成功
                            end if;
                        elsif state = s1 then
                            state = s2; -- 已经有抢答
                        end if;
            end case;                        
    end process;

    -- 根据状态设置数据
    output: process(k1, k2, k3, k4, state, num_led_temp)
    begin
        case state is
            when s0 => num_led_temp = "0000"; led7_temp = "";
            when s1 => if k1 = '1' then
                            num_led_temp = "0001"; led7_temp = "";
                        elsif k2 = '1' then
                            num_led_temp = "0010"; led7_temp = "";
                        elsif k3 = '1' then
                            num_led_temp = "0100"; led7_temp = "";
                        elsif k4 = '1' then
                            num_led_temp = "1000"; led7_temp = "";
                        end if;
        end case;

        num_led <= num_led_temp;
        led7 <= led7_temp;
    end process;

end behave;


